﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HDJ.Framework.Core
{
    /// <summary>
    /// 管理多个动态变量
    /// </summary>
    public class MultiDynamicValueRecordController
    {
        private List<DynamicValue> recordEventValues = new List<DynamicValue>();
        private List<DynamicValue> recordValues = new List<DynamicValue>();
        private int storeIndex = -1;
        public void Add(DynamicValue value)
        {
            recordValues.Add(value);
            value.onValueChangeEvent += OnValueChangeEvent;
        }

        private void OnValueChangeEvent(DynamicValue dynamicValue, object nowValue, object lastValue)
        {
            if (storeIndex != -1 && storeIndex != recordEventValues.Count)
            {
                recordEventValues.RemoveRange(storeIndex, recordEventValues.Count - storeIndex);
            }
   
            recordEventValues.Add(dynamicValue);
            storeIndex = recordEventValues.Count;
        }

        public void Undo()
        {
            if (storeIndex <= 0)
                return;
            storeIndex--;
            recordEventValues[storeIndex].Undo(false);
        }
        public void Redo()
        {
            if (storeIndex == recordEventValues.Count)
                return;
            recordEventValues[storeIndex].Redo(false);
            storeIndex++;
        }
        public void StoreValue()
        {
            foreach (var item in recordValues)
            {
                item.StoreValue();
            }
            //recordEventValues.RemoveRange(storeIndex, recordEventValues.Count - storeIndex);
            //storeIndex = recordEventValues.Count;
        }
        public bool IsHaveChangeValue
        {
            get
            {
                foreach (var item in recordValues)
                {
                    if (item.IsChange)
                        return true;
                }
                return false;
            }
        }
        public void Clear()
        {
            recordEventValues.Clear();
            recordValues.Clear();
        }
    }
}
